import React, { useEffect, useState } from 'react';
import { ConfigProvider } from '@alifd/next';
import { i18n } from '@lingui/core';
import { I18nProvider } from '@lingui/react';
import { getLocale } from '@tau/utils';
import { default as messages } from '@/locales';
import { messages as tauMessages } from '@tau/ui';


import fusion_en_US from '@alifd/next/lib/locale/en-us';
import fusion_zh_CN from '@alifd/next/lib/locale/zh-cn'; // 引入 locale 配置文件

// const LOCALE = 'en-US';
const LOCALE = getLocale(SCOPE);


_.merge(messages, tauMessages);

i18n.load(messages);
i18n.activate(LOCALE);

const localeInfo = {
  'zh-CN': fusion_zh_CN,
  'en-US': fusion_en_US,
};
const fusionLang = localeInfo[LOCALE] ? localeInfo[LOCALE] : localeInfo['zh-CN'];


function LocaleProvider({ children }) {
  const [device, setDevice] = useState(getDevice(NaN));

  function getDevice(width) {
    const _isPhone =
      typeof navigator !== 'undefined' &&
      navigator &&
      navigator.userAgent.match(/phone/gi);

    if (width < 680 || _isPhone) {
      return 'phone';
    } else if (width < 1280 && width > 680) {
      return 'tablet';
    } else {
      return 'desktop';
    }
  }

  useEffect(() => {
    if (typeof window !== 'undefined') {
      window.addEventListener('optimizedResize', (e) => {
        const deviceWidth = (e && e.target && e.target.innerWidth) || NaN;
        setDevice(getDevice(deviceWidth));
      });
    }
  }, []);


  return (
    <I18nProvider i18n={i18n}>
      <ConfigProvider locale={fusionLang} device={device}>{React.Children.only(children)}</ConfigProvider>
    </I18nProvider>
  );
}

export default LocaleProvider;
